package org.jeecg.common.util;

import com.google.common.collect.Lists;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

//用于调用统计接口s
public class HttpUtils  {
	static Logger log = LoggerFactory.getLogger(HttpUtils.class);
  private static final String APPLICATION_JSON = "application/json";

public static String httpPostWithJSON(String url, String json) throws Exception {
	  // 将JSON进行UTF-8编码,以便传输中文
/*	    String encoderJson = URLEncoder.encode(json,"UTF-8");*/
	  	String result=null;
	   CloseableHttpClient httpClient = HttpClients.createDefault();
	   HttpPost httpPost = new HttpPost(url);
	   httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json;charset=utf-8");
	   BufferedReader in=null;
	   StringEntity se = new StringEntity(json,"UTF-8");
	   se.setContentType(APPLICATION_JSON);
	   se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON));
	   httpPost.setEntity(se);
	   HttpResponse response = httpClient.execute(httpPost);
	   /**请求发送成功，并得到响应**/
	   if (response.getStatusLine().getStatusCode() == 200) {
	  	  in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(),"utf-8"));  
	        StringBuffer sb = new StringBuffer("");  
	        String line = "";  
	        String NL = System.getProperty("line.separator");  
	        while ((line = in.readLine()) != null) {  
	            sb.append(line + NL);  
	        }  
	        in.close();  
	        result = sb.toString();
	   }
	   return result;
	  }

	public static String myUrlHead(String strUrl,Map params,Map<String,String> headParams,String method){
		HttpURLConnection conn = null;
		BufferedReader br = null;
		StringBuffer sb = new StringBuffer();
		try {
			if((method == null || method.equals("GET")) && params != null){
				strUrl = strUrl+"?"+urlencode(params);
			}
			log.info(strUrl);
			URL url = new URL(strUrl);
			conn = (HttpURLConnection) url.openConnection();
			if(method == null || method.equals("GET")){
				conn.setRequestMethod("GET");
			} else {
				conn.setRequestMethod("POST");
				conn.setDoOutput(true);
			}
			for (Map.Entry<String,String> e: headParams.entrySet()){
				conn.setRequestProperty(e.getKey(),e.getValue());
			}
			System.setProperty("desn.tunnel.qydev.com", "true");
			conn.setUseCaches(false);
			conn.setConnectTimeout(30000);
			conn.setReadTimeout(30000);
			conn.setInstanceFollowRedirects(false);
			conn.connect();
			InputStream is =  conn.getInputStream();
			br = new BufferedReader(new InputStreamReader(is, "utf-8"));
			String strReader = null;
			while( (strReader = br.readLine()) !=null){
				sb.append(strReader);
			}
			br.close();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		} finally{
			if(br != null){
				try {
					br.close();
				} catch (IOException e) {
					log.error(e.getMessage(), e);
				}
			}
			if(conn != null){
				conn.disconnect();
			}
		}
		return sb.toString();
	}


/**
 * 调用外部接口--
 * @param strUrl
 * @param params
 * @param method
 */
public static String myUrl(String strUrl, Map params,String method){	
	HttpURLConnection conn = null;
	BufferedReader br = null;
	StringBuffer sb = new StringBuffer();
	try {
		if(method== null || method.equals("GET") || "PUT".equals(method)){
			strUrl = strUrl+"?"+urlencode(params);
		}
		log.info(strUrl);
		URL url = new URL(strUrl);
		conn = (HttpURLConnection) url.openConnection();
		if(method == null || method.equals("GET")){
			conn.setRequestMethod("GET");
		} else if ("POST".equals(method)){
			conn.setRequestMethod(method);
			conn.setDoOutput(true);
		} else if ("PUT".equals(method)){
			conn.setRequestMethod(method);
			conn.setDoOutput(true);
		}
		conn.setUseCaches(false);
		conn.setConnectTimeout(30000);
		conn.setReadTimeout(30000);
		conn.setInstanceFollowRedirects(false);
		conn.connect();
		InputStream is =  conn.getInputStream();
		br = new BufferedReader(new InputStreamReader(is, "utf-8"));
		String strReader = null;
		while( (strReader = br.readLine()) !=null){
			sb.append(strReader);
		}
		br.close();
	} catch (Exception e) {
		log.error(e.getMessage(), e);
	} finally{
		if(br != null){
			try {
				br.close();
			} catch (IOException e) {
				log.error(e.getMessage(), e);
			}
		}
		if(conn != null){
			conn.disconnect();
		}
	}
	return sb.toString();
}

	public static String httpGetURI(String url) throws Exception {

		try (CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultRequestConfig(ComUtil.requestConfig)
				.build()) {

			URL u_rl = new URL(url);
			URI uri = new URI(u_rl.getProtocol(), u_rl.getHost(), u_rl.getPath(), u_rl.getQuery(), null);
			HttpGet httpget = new HttpGet(uri);

			// post请求
			try (CloseableHttpResponse httpResponse = httpclient.execute(httpget)) {
				int status = httpResponse.getStatusLine().getStatusCode();
				if (status >= 200 && status < 300) {
					HttpEntity httpEntity = httpResponse.getEntity();
					return httpEntity != null ? EntityUtils.toString(httpEntity) : null;
				} else {
					throw new RuntimeException("Unexpected response status: " + httpResponse.getStatusLine());
				}
			}
		}
	}
private static final int timeout = 90 * 1000; // 90 seconds
public static final RequestConfig requestConfig = RequestConfig.custom()
        .setConnectTimeout(timeout)
        .setConnectionRequestTimeout(timeout)
        .setSocketTimeout(timeout).build();
public static String myUrlPost(String url, String body) throws RuntimeException {
	// HttpClient
	try (CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig)
			.build()) {

		HttpPost httpPost = new HttpPost(url);
		// 创建参数
		StringEntity entity = new StringEntity(body, "UTF-8");
		
		httpPost.setEntity(entity);

		// post请求
		try (CloseableHttpResponse httpResponse = closeableHttpClient.execute(httpPost)) {
			int status = httpResponse.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                HttpEntity httpEntity = httpResponse.getEntity();
                return httpEntity != null ? EntityUtils.toString(httpEntity, "UTF8") : null;
            } else {
                throw new RuntimeException("Unexpected response status: " + httpResponse.getStatusLine());
            }
		}
	} catch (Exception ex) {
		throw new RuntimeException(ex);
	}
}
//将map型转为请求参数型
public static String urlencode(Map<String,Object> data) {
    StringBuilder sb = new StringBuilder();
    for (Map.Entry i : data.entrySet()) {
        try {
            sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage(), e);
        }
    }
    return sb.toString();
}

}
